$(document).ready(function () {


    layui.use(function () {



        // 表格
        form = layui.form;


        laydate = layui.laydate;

        form.on('select(nameType)', function (data) {//状态下拉
            $('div[lay-filter="search"]').click();
        });

        form.on('submit(search)', function (data) {//监听查询提交
            params = data.field;
            queryTableList(1)
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        form.on('radio(event-filter)', function (data) {

            tableParams.type = data.value
            queryTable(1)

        });
        form.on('submit(edit)', function (data) {//监听新增修改提交
            data.field.personId = curPid;
            let msgType = "";
            if (curId) {
                msgType = "编辑"
                data.field.id = curId
            } else {
                msgType = "新增"
            }


            if (
                curOpType == 2
            ) {
                data.field.beginTime = data.field.beginTime + ' ' + (data.field.t1 == 1 ? '08:00:00' : '12:00:00');
                data.field.endTime = data.field.endTime + ' ' + (data.field.t2 == 1 ? '12:00:00' : '18:00:00');
            }

            new AjaxChain()
                .setUrl((curOpType == 1 ? "/person/honor/save" : "/person/off/save"))
                .setMethod('post')
                .setData(JSON.stringify(data.field))
                .then(data => {
                    layer.close(drawer);
                    layer.msg(msgType + '成功', { icon: 1, time: 2000 });
                    queryTable()
                })
                .catch(err => {
                    console.error('请求异常:', err);
                })
                .send();

            return false;
        });
        initSubMenu();
        queryTableList(1);
        queryMen()

    });
})
var params = {};//查询条件参数
var form, unit;
var drawer;//抽屉实例
var curPid = null;//当前选中人员

var laydate = null;


// 查询人员下拉
queryMen = () => {
    new AjaxChain()
        .setUrl('/person/list')
        .setData({
            pageNum: 1,
            pageSize: 999
        })
        .then(data => {
            typeStr = data.data.reduce((x, y) => {
                return x + `<option value="${y.name}">${y.name}</option>`
            }, '<option value="">名称(可搜索)</option>')

            $('#search-men').empty().append(typeStr)

            form.render('select');
        })
        .send();
}

// 节点分页
queryTablePage = (total) => {

    var laypage = layui.laypage;


    laypage.render({
        elem: 'card-page',
        count: total,
        limit: 8,
        groups: 3,
        prev: '<i class="layui-icon layui-icon-left"></i>',
        next: '<i class="layui-icon layui-icon-right"></i>',
        layout: ['prev', 'page', 'next', 'count'],
        jump: function (obj, first) {

            if (!first) {

                queryTableList(obj.curr)

            }

        }

    });


}

//查询节点列表
queryTableList = (pN) => {
    params.pageNum = pN
    params.pageSize = 8;

    new AjaxChain()
        .setUrl('/person/list')
        .setData(params)
        .then(data => {

            if (pN == 1) {
                queryTablePage(data.total)
            }

            if (data.total == 0) {
                $('.card-content').empty().append('<div class="no-data">未查询到人员数据</div>')
                return
            }

            $('.card-content').empty()
                .append(
                    data.data.reduce(
                        (x, y) => {
                            return x +
                                `<div class="card-item gradient-card" onclick='manCardDetail(${JSON.stringify(y)})'>
                                    <div class="gradient-card1">
                                        <div class="card-item-title">
                                            <img src="${y.photoPath ? ('/images/' + y.photoPath) : '../static/img/photo.png'}">
                                            <div class="card-item-title1">
                                                <div class="card-item-title1-name">
                                                    ${y.name}
                                                </div>
                                                <div>
                                                    <span class="layui-badge layui-bg-blue">${y.genderDesc || '-'}</span>
                                                    <span class="layui-badge layui-bg-green">${y.professionalTitleDesc || '-'}</span>
                                                    <span class="layui-badge layui-bg-cyan">${$.calculateAge(y.birthDate)}岁</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="card-item-con">
                                                <div>民族：${y.nation || ''}</div>
                                                <div>政治面貌：${y.politicalStatusDesc || ''}</div>
                                                <div>职务：${y.postDesc || ''}</div>
                                                <div>专业岗位：${y.positionalPositionDesc || ''}</div>
                                                <div>联系方式：${y.cellphone || ''}</div>
                                                <div>入职日期：${y.workDate || ''}</div>
                                        </div>
                                    </div>
                                </div>`
                        }, ''
                    ))

        })
        .catch(err => {
            console.error('请求异常:', err);
        })
        .send();
}

// 展开详情
function manCardDetail(res) {

    $('#cards-list').hide()
    $('#card-detail').show()

    $('.card-item-in').empty().append(
        `<div class="card-item-title">
                            <img src="${res.photoPath ? ('/images/' + res.photoPath) : '../static/img/photo.png'}">
                            <div class="card-item-title1">
                                <div class="card-item-title1-name">
                                    ${res.name}
                                </div>
                                <div>
                                    <span class="layui-badge layui-bg-blue">${res.genderDesc || '-'}</span>
                                    <span class="layui-badge layui-bg-green">${res.professionalTitleDesc || '-'}</span>
                                    <span class="layui-badge layui-bg-cyan">${$.calculateAge(res.birthDate)}岁</span>
                                </div>
                            </div>
                        </div>
                        <div class="card-item-con">
                            <div>民族：${res.nation || '-'} </div>
                            <div>联系方式：${res.cellphone || '-'} </div>
                            <div>受教育程度：${res.educationDesc || '-'} </div>
                            <div>入职日期：${res.workDate || '-'} </div>
                            <div>休假情况：${res.vacationStatusDesc || '-'} </div>
                            <div>籍贯：${res.nativePlace || '-'} </div>
                            <div>专业岗位：${res.positionalPositionDesc || '-'} </div>
                            <div>政治面貌：${res.politicalStatusDesc || '-'} </div>
                            <div>出生日期：${res.birthDate || '-'} </div>
                            <div>有无房产：${res.hasHouseDesc || '-'} </div>
                            <div>职务：${res.postDesc || '-'} </div>
                            <div>rfid号：${res.rfidName || '-'} </div>
                            <div>入党团日期：${res.politicalTime || '-'} </div>
                            <div>婚姻情况：${res.maritalStatusDesc || '-'} </div>
                            <div>有无子女：${res.hasChildDesc || '-'} </div>
                        </div>
        
        `
    )



    curPid = res.id;

    $('.card-tab-item').eq(0).click()


    new AjaxChain()
        .setUrl("/person/off/count")
        .setData({ personId: res.id })
        .then(data => {

            $('.off-box').empty().append(
                `           <div class="off-item">请假总数 ${data.total}</div>
                            <div class="off-item">近一年请假数 ${data.oneYear}</div>
                            <div class="off-item">近三个月请假数 ${data.threeMonth}</div>
                `
            )


        })
        .catch(err => {
            console.error('请求异常:', err);
        })
        .send();

    tableParams.type = '';
    $('input[type="radio"][name="type"][value=""]').prop('checked', true);

}



// 返回人员列表

function rebackList() {
    $('#cards-list').show()
    $('#card-detail').hide()
}

// 详情切换
var curOpType = 1;
$('.card-tab-item').click(function (e) {
    $(e.currentTarget).addClass('active').siblings().removeClass('active');

    var type = $(e.currentTarget).data().type
    type == 1 ? $(".off-show").hide() : $(".off-show").show()


    $('.card-tab-content').hide();
    $('.card-tab' + type).show();

    curOpType = type;

    queryTable()


})



// 查询列表
var tableParams = {}
queryTable = () => {
    tableParams.pageSize = 10;
    tableParams.personId = curPid;


    var cols = [];

    if (curOpType == 1) {
        cols = [ //标题栏
            { field: 'honorName', title: '荣誉名称', align: "center" }
            , { field: 'honorLevelDesc', title: '奖项类型', align: "center" }
            , { field: 'honorTypeDesc', title: '奖项级别', align: "center" }
            , { field: 'honorDate', title: '获奖时间', align: "center" }
            , {
                flex: 'right',
                title: '操作',
                align: 'center',
                templet: function (d) {
                    let res = JSON.stringify(d);
                    return `<div class="table-tool">
                            <div onclick='tableHandle(2,${res})' class="table-del layui-btn">
                              <img src="../static/img/del.png">删除
                            </div>
                          </div>`;
                },
            },

        ]
    } else {
        cols = [ //标题栏
            {
                field: 'beginTime', title: '开始时间', align: "center"
                , templet: function (d) {


                    var time = d.beginTime.split(' ')[0]


                    return time + ' ' + (d.beginTime.indexOf('08:00:00') > -1 ? '上午' : '下午')
                },
            }
            , {
                field: 'endTime', title: '结束时间', align: "center"
                , templet: function (d) {


                    var time = d.endTime.split(' ')[0]


                    return time + ' ' + (d.endTime.indexOf('12:00:00') > -1 ? '上午' : '下午')
                },
            }
            , {
                field: 'honorLevelDesc', title: '请假天数', align: "center"
                , templet: function (d) {

                    let hours = calculateFullHours(d.beginTime, d.endTime) / 24 + '';

                    [dayT, harfT] = hours.split('.');

                    let t = 0;
                    if (harfT == undefined) {
                        t = 0;
                    } else if (harfT.indexOf("416") > -1) {
                        t = 1;
                    } else {
                        t = 0.5
                    }

                    return parseInt(dayT) + t;



                    console.log(calculateFullHours("2025-04-17 08:00:00", "2025-04-18 12:00:00") / 24);//+0.5
                    console.log(calculateFullHours("2025-04-17 08:00:00", "2025-04-18 18:00:00") / 24);//+1
                    console.log(calculateFullHours("2025-04-17 12:00:00", "2025-04-18 12:00:00") / 24);//+0
                    console.log(calculateFullHours("2025-04-17 12:00:00", "2025-04-18 18:00:00") / 24);//+0.5



                },
            }
            , { field: 'typeDesc', title: '请假类型', align: "center" }
            , { field: 'reason', title: '请假说明', align: "center" }
            , { field: 'destination', title: '前往城市', align: "center" }
            , {
                flex: 'right',
                title: '操作',
                align: 'center',
                templet: function (d) {
                    let res = JSON.stringify(d);
                    return `<div class="table-tool">
                            <div onclick='tableHandle(2,${res})' class="table-del layui-btn">
                              <img src="../static/img/del.png">删除
                            </div>
                          </div>`;
                },
            },

        ]
    }


    layui.use('table', function () {
        var table = layui.table;

        //展示已知数据
        table.render({
            elem: '#table'
            , text: {
                none: '暂无数据'
            }
            , method: 'get'
            , url: ajaxPrefix() + (curOpType == 1 ? "/person/honor/list" : "/person/off/list")
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , where: tableParams
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: [cols]
            , height: 'full'
            // ,skin: 'line' //表格风格
            , even: true
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 3 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页

            }
            , done: function (res, curr, count) {

                $('.layui-table-cell').height($('#card-detail .contain-table-list').height() / 15);
            },

        });

    });
}





// 列表功能按钮操作
tableHandle = (type, res) => {
    switch (type) {
        case 1://编辑
            curId = res.id
            openDrawer(2, res)
            break;
        case 2://删除

            layer.confirm('确定删除该记录吗？', { icon: 3 }, function () {

                new AjaxChain()
                    .setUrl((curOpType == 1 ? "/person/honor/delete" : "/person/off/delete"))
                    .setData({ id: res.id })
                    .then(data => {
                        layer.msg('删除成功', { icon: 1, time: 1500 });
                        queryTable();
                    })
                    .catch(err => {
                        console.error('请求异常:', err);
                    })
                    .send();
            });
            break;

        case 3://新增 
            curId = null;
            openDrawer(1)
            break;


        default:
            break;
    }
}





openDrawer = (type, res) => {
    drawer = layer.open({
        title: (type == 1 ? "新增" : "编辑") + (curOpType == 1 ? "荣誉" : "请假登记"),
        type: 1,
        offset: 'r',
        anim: 'slideLeft', // 从右往左
        area: ['30%', '100%'],
        shade: 0.3,
        shadeClose: false,
        id: 'edit-offset',
        success: function (layero, index, that) {


            if (curOpType == 1) {
                laydate.render({
                    elem: '#honorDate',
                });
            } else {
                laydate.render({
                    elem: '#beginTime',
                });
                laydate.render({
                    elem: '#endTime',
                });
            }

            if (res) {
                form.val('editForm', res);

            } else {
                form.render(null, 'editForm');
            }
        },
        content: $(`#templet${curOpType}`).html()
    });

}


function calculateFullHours(time1, time2) {
    const date1 = new Date(time1);
    const date2 = new Date(time2);
    const diffInMilliseconds = Math.abs(date2 - date1);
    const fullHours = Math.floor(diffInMilliseconds / (1000 * 60 * 60));
    return fullHours;
}